{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用 distilabel 生成偏好数据集\n",
    "\n",
    "_作者：[David Berenstein](https://huggingface.co/davidberenstein1957) 和 [Sara Han Díaz](https://huggingface.co/sdiazlor)_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **库**: [argilla](https://github.com/argilla-io/argilla), [hf-inference-endpoints](https://github.com/huggingface/huggingface_hub)\n",
    "- **组件**: [LoadDataFromHub](https://distilabel.argilla.io/latest/components-gallery/steps/loaddatafromhub/), [TextGeneration](https://distilabel.argilla.io/latest/components-gallery/tasks/textgeneration/), [UltraFeedback](https://distilabel.argilla.io/latest/components-gallery/tasks/ultrafeedback/), [GroupColumns](https://distilabel.argilla.io/latest/components-gallery/steps/groupcolumns/), [FormatTextGenerationDPO](https://distilabel.argilla.io/latest/components-gallery/steps/formattextgenerationdpo/), [PreferenceToArgilla](https://distilabel.argilla.io/latest/components-gallery/steps/textgenerationtoargilla/), [InferenceEndpointsLLM](https://distilabel.argilla.io/latest/components-gallery/llms/inferenceendpointsllm/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在本教程中，我们将使用 **distilabel** 生成一个用于 DPO、ORPO 或 RLHF 的合成偏好数据集。**distilabel** 是一个为工程师设计的合成数据和 AI 反馈框架，旨在提供基于经过验证的研究论文的快速、可靠和可扩展的管道。请查看[文档](https://distilabel.argilla.io/latest/)了解更多信息。\n",
    "\n",
    "为了生成响应并对其进行评估，我们将使用与 **distilabel** 集成的 [无服务器 HF 推理 API](https://huggingface.co/docs/api-inference/index)。该服务是免费的，但有使用限制，允许您通过简单的 HTTP 请求测试和评估超过 150,000 个公开模型，或您自己的私有模型，推理速度快，托管在 Hugging Face 的共享基础设施上。如果您需要更多计算能力，可以使用 [Hugging Face 推理端点](https://huggingface.co/docs/inference-endpoints/guides/create_endpoint)部署您自己的推理端点。\n",
    "\n",
    "最后，为了进一步整理数据，我们将使用 [Argilla](https://github.com/argilla-io/argilla)，它允许我们对数据质量提供人工反馈。Argilla 是一个为 AI 工程师和领域专家设计的协作工具，帮助他们为项目构建高质量的数据集。请查看 [文档](https://docs.argilla.io/latest/) 了解更多信息。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 开始"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 安装依赖\n",
    "\n",
    "为了完成本教程，您需要通过 pip 安装 distilabel SDK 和一些第三方库。由于本教程中将使用 **免费的但有使用限制的 Hugging Face 无服务器推理 API**，因此我们需要额外安装该依赖。您可以通过运行以下命令来安装所有必要的依赖："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install \"distilabel[hf-inference-endpoints]\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install \"transformers~=4.0\" \"torch~=2.0\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "让我们进行所需的导入："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from distilabel.llms import InferenceEndpointsLLM\n",
    "from distilabel.pipeline import Pipeline\n",
    "from distilabel.steps import (\n",
    "    LoadDataFromHub,\n",
    "    GroupColumns,\n",
    "    FormatTextGenerationDPO,\n",
    "    PreferenceToArgilla,\n",
    ")\n",
    "from distilabel.steps.tasks import TextGeneration, UltraFeedback"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你需要一个 `HF_TOKEN` 来使用 HF 推理端点。请登录以便在此 Notebook 中直接使用它。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from huggingface_hub import login\n",
    "\n",
    "login(token=os.getenv(\"HF_TOKEN\"), add_to_git_credential=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### （可选）部署 Argilla\n",
    "\n",
    "你可以跳过此步骤或将其替换为任何其他数据评估工具，但如果缺乏数据质量，你的模型质量将受到影响，因此我们建议查看您的数据。如果你已经部署了 Argilla，可以跳过此步骤。否则，你可以按照 [此指南](https://docs.argilla.io/latest/getting_started/quickstart/) 快速部署 Argilla。\n",
    "\n",
    "同时，你需要将 Argilla 安装为 distilabel 的附加依赖。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install \"distilabel[argilla, hf-inference-endpoints]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义管道"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了生成我们的偏好数据集，我们需要定义一个包含所有必要步骤的 `Pipeline`。接下来，我们将详细介绍每个步骤。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 加载数据集\n",
    "\n",
    "我们将使用来自 Hugging Face Hub 的 [`argilla/10Kprompts-mini`](https://huggingface.co/datasets/argilla/10Kprompts-mini) 数据集作为源数据。\n",
    "\n",
    "<iframe\n",
    "  src=\"https://huggingface.co/datasets/argilla/10Kprompts-mini/embed/viewer/default/train\"\n",
    "  frameborder=\"0\"\n",
    "  width=\"100%\"\n",
    "  height=\"560px\"\n",
    "></iframe>\n",
    "\n",
    "- 组件: `LoadDataFromHub`\n",
    "- 输入列: `instruction` 和 `topic`，与加载的数据集中的列相同\n",
    "- 输出列: `instruction` 和 `topic`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([{'instruction': 'How can I create an efficient and robust workflow that utilizes advanced automation techniques to extract targeted data, including customer information, from diverse PDF documents and effortlessly integrate it into a designated Google Sheet? Furthermore, I am interested in establishing a comprehensive and seamless system that promptly activates an SMS notification on my mobile device whenever a new PDF document is uploaded to the Google Sheet, ensuring real-time updates and enhanced accessibility.',\n",
       "   'topic': 'Software Development'}],\n",
       " True)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "load_dataset = LoadDataFromHub(\n",
    "        repo_id= \"argilla/10Kprompts-mini\",\n",
    "        num_examples=1,\n",
    "        pipeline=Pipeline(name=\"showcase-pipeline\"),\n",
    "    )\n",
    "load_dataset.load()\n",
    "next(load_dataset.process())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 生成响应\n",
    "\n",
    "我们需要为给定的指令生成响应。我们将使用通过无服务器推理 API 在 Hugging Face Hub 上提供的两个不同模型：[`meta-llama/Meta-Llama-3-8B-Instruct`](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct) 和 [`mistralai/Mixtral-8x7B-Instruct-v0.1`](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1)。我们还将为每个模型指定生成参数。\n",
    "\n",
    "- 组件: `TextGeneration` 任务，使用 `InferenceEndpointsLLM` 调用 LLM\n",
    "- 输入列: `instruction`\n",
    "- 输出列: `generation`、`distilabel_metadata`、`model_name`，针对每个模型\n",
    "\n",
    "根据你的使用案例并为提高结果，你可以选择使用任何 [其他 LLM](https://distilabel.argilla.io/latest/components-gallery/llms/)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[{'instruction': 'Which are the top cities in Spain?', 'generation': 'Spain is a country with a rich culture, history, and architecture, and it has many great cities to visit. Here are some of the top cities in Spain:\\n\\n1. **Madrid**: The capital city of Spain, known for its vibrant nightlife, museums, and historic landmarks like the Royal Palace and Prado Museum.\\n2. **Barcelona**: The second-largest city in Spain, famous for its modernist architecture, beaches, and iconic landmarks like La Sagrada Família and Park Güell, designed by Antoni Gaudí.\\n3. **Valencia**: Located on the Mediterranean coast, Valencia is known for its beautiful beaches, City of Arts and Sciences, and delicious local cuisine, such as paella.\\n4. **Seville**: The capital of Andalusia, Seville is famous for its stunning cathedral, Royal Alcázar Palace, and lively flamenco music scene.\\n5. **Málaga**: A coastal city in southern Spain, Málaga is known for its rich history, beautiful beaches, and being the birthplace of Pablo Picasso.\\n6. **Zaragoza**: Located in the northeastern region of Aragon, Zaragoza is a city with a rich history, known for its Roman ruins, Gothic cathedral, and beautiful parks.\\n7. **Granada**: A city in the Andalusian region, Granada is famous for its stunning Alhambra palace and generalife gardens, a UNESCO World Heritage Site.\\n8. **Bilbao**: A city in the Basque Country, Bilbao is known for its modern architecture, including the Guggenheim Museum, and its rich cultural heritage.\\n9. **Alicante**: A coastal city in the Valencia region, Alicante is famous for its beautiful beaches, historic castle, and lively nightlife.\\n10. **San Sebastián**: A city in the Basque Country, San Sebastián is known for its stunning beaches, gastronomic scene, and cultural events like the San Sebastián International Film Festival.\\n\\nThese are just a few of the many great cities in Spain, each with its own unique character and attractions.', 'distilabel_metadata': {'raw_output_text_generation_0': 'Spain is a country with a rich culture, history, and architecture, and it has many great cities to visit. Here are some of the top cities in Spain:\\n\\n1. **Madrid**: The capital city of Spain, known for its vibrant nightlife, museums, and historic landmarks like the Royal Palace and Prado Museum.\\n2. **Barcelona**: The second-largest city in Spain, famous for its modernist architecture, beaches, and iconic landmarks like La Sagrada Família and Park Güell, designed by Antoni Gaudí.\\n3. **Valencia**: Located on the Mediterranean coast, Valencia is known for its beautiful beaches, City of Arts and Sciences, and delicious local cuisine, such as paella.\\n4. **Seville**: The capital of Andalusia, Seville is famous for its stunning cathedral, Royal Alcázar Palace, and lively flamenco music scene.\\n5. **Málaga**: A coastal city in southern Spain, Málaga is known for its rich history, beautiful beaches, and being the birthplace of Pablo Picasso.\\n6. **Zaragoza**: Located in the northeastern region of Aragon, Zaragoza is a city with a rich history, known for its Roman ruins, Gothic cathedral, and beautiful parks.\\n7. **Granada**: A city in the Andalusian region, Granada is famous for its stunning Alhambra palace and generalife gardens, a UNESCO World Heritage Site.\\n8. **Bilbao**: A city in the Basque Country, Bilbao is known for its modern architecture, including the Guggenheim Museum, and its rich cultural heritage.\\n9. **Alicante**: A coastal city in the Valencia region, Alicante is famous for its beautiful beaches, historic castle, and lively nightlife.\\n10. **San Sebastián**: A city in the Basque Country, San Sebastián is known for its stunning beaches, gastronomic scene, and cultural events like the San Sebastián International Film Festival.\\n\\nThese are just a few of the many great cities in Spain, each with its own unique character and attractions.'}, 'model_name': 'meta-llama/Meta-Llama-3-8B-Instruct'}]\n",
      "[{'instruction': 'Which are the top cities in Spain?', 'generation': ' Here are some of the top cities in Spain based on various factors such as tourism, culture, history, and quality of life:\\n\\n1. Madrid: The capital and largest city in Spain, Madrid is known for its vibrant nightlife, world-class museums (such as the Prado Museum and Reina Sofia Museum), stunning parks (such as the Retiro Park), and delicious food.\\n\\n2. Barcelona: Famous for its unique architecture, Barcelona is home to several UNESCO World Heritage sites designed by Antoni Gaudí, including the Sagrada Familia and Park Güell. The city also boasts beautiful beaches, a lively arts scene, and delicious Catalan cuisine.\\n\\n3. Valencia: A coastal city located in the east of Spain, Valencia is known for its City of Arts and Sciences, a modern architectural complex that includes a planetarium, opera house, and museum of interactive science. The city is also famous for its paella, a traditional Spanish dish made with rice, vegetables, and seafood.\\n\\n4. Seville: The capital of Andalusia, Seville is famous for its flamenco dancing, stunning cathedral (the largest Gothic cathedral in the world), and the Alcázar, a beautiful palace made up of a series of rooms and courtyards.\\n\\n5. Granada: Located in the foothills of the Sierra Nevada mountains, Granada is known for its stunning Alhambra palace, a Moorish fortress that dates back to the 9th century. The city is also famous for its tapas, a traditional Spanish dish that is often served for free with drinks.\\n\\n6. Bilbao: A city in the Basque Country, Bilbao is famous for its modern architecture, including the Guggenheim Museum, a contemporary art museum designed by Frank Gehry. The city is also known for its pintxos, a type of Basque tapas that are served in bars and restaurants.\\n\\n7. Málaga: A coastal city in Andalusia, Málaga is known for its beautiful beaches, historic sites (including the Alcazaba and Gibralfaro castles), and the Picasso Museum, which is dedicated to the famous Spanish artist who was born in the city.\\n\\nThese are just a few of the many wonderful cities in Spain.', 'distilabel_metadata': {'raw_output_text_generation_0': ' Here are some of the top cities in Spain based on various factors such as tourism, culture, history, and quality of life:\\n\\n1. Madrid: The capital and largest city in Spain, Madrid is known for its vibrant nightlife, world-class museums (such as the Prado Museum and Reina Sofia Museum), stunning parks (such as the Retiro Park), and delicious food.\\n\\n2. Barcelona: Famous for its unique architecture, Barcelona is home to several UNESCO World Heritage sites designed by Antoni Gaudí, including the Sagrada Familia and Park Güell. The city also boasts beautiful beaches, a lively arts scene, and delicious Catalan cuisine.\\n\\n3. Valencia: A coastal city located in the east of Spain, Valencia is known for its City of Arts and Sciences, a modern architectural complex that includes a planetarium, opera house, and museum of interactive science. The city is also famous for its paella, a traditional Spanish dish made with rice, vegetables, and seafood.\\n\\n4. Seville: The capital of Andalusia, Seville is famous for its flamenco dancing, stunning cathedral (the largest Gothic cathedral in the world), and the Alcázar, a beautiful palace made up of a series of rooms and courtyards.\\n\\n5. Granada: Located in the foothills of the Sierra Nevada mountains, Granada is known for its stunning Alhambra palace, a Moorish fortress that dates back to the 9th century. The city is also famous for its tapas, a traditional Spanish dish that is often served for free with drinks.\\n\\n6. Bilbao: A city in the Basque Country, Bilbao is famous for its modern architecture, including the Guggenheim Museum, a contemporary art museum designed by Frank Gehry. The city is also known for its pintxos, a type of Basque tapas that are served in bars and restaurants.\\n\\n7. Málaga: A coastal city in Andalusia, Málaga is known for its beautiful beaches, historic sites (including the Alcazaba and Gibralfaro castles), and the Picasso Museum, which is dedicated to the famous Spanish artist who was born in the city.\\n\\nThese are just a few of the many wonderful cities in Spain.'}, 'model_name': 'mistralai/Mixtral-8x7B-Instruct-v0.1'}]\n"
     ]
    }
   ],
   "source": [
    "generate_responses = [\n",
    "    TextGeneration(\n",
    "        llm=InferenceEndpointsLLM(\n",
    "            model_id=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n",
    "            tokenizer_id=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n",
    "            generation_kwargs={\"max_new_tokens\": 512, \"temperature\": 0.7},\n",
    "        ),\n",
    "        pipeline=Pipeline(name=\"showcase-pipeline\"),\n",
    "    ),\n",
    "    TextGeneration(\n",
    "        llm=InferenceEndpointsLLM(\n",
    "            model_id=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
    "            tokenizer_id=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
    "            generation_kwargs={\"max_new_tokens\": 512, \"temperature\": 0.7},\n",
    "        ),\n",
    "        pipeline=Pipeline(name=\"showcase-pipeline\"),\n",
    "    ),\n",
    "]\n",
    "for task in generate_responses:\n",
    "    task.load()\n",
    "    print(next(task.process([{\"instruction\": \"Which are the top cities in Spain?\"}])))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 组响应\n",
    "\n",
    "该任务需要评估响应，并且输入需要一个生成列表。然而，每个模型的响应都保存在子集 `text_generation_0` 和 `text_generation_1` 的 `generation` 列中。我们将把这两列合并成一个单一的列，并应用于 `default` 子集。\n",
    "\n",
    "- 组件：`GroupColumns`\n",
    "- 输入列：来自 `text_generation_0` 和 `text_generation_1` 的 `generation` 和 `model_name`\n",
    "- 输出列：`generations` 和 `model_names`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'generations': ['Madrid', 'Barcelona'],\n",
       "  'model_names': ['meta-llama/Meta-Llama-3-8B-Instruct',\n",
       "   'mistralai/Mixtral-8x7B-Instruct-v0.1']}]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "group_responses = GroupColumns(\n",
    "    columns=[\"generation\", \"model_name\"],\n",
    "    output_columns=[\"generations\", \"model_names\"],\n",
    "    pipeline=Pipeline(name=\"showcase-pipeline\"),\n",
    ")\n",
    "next(\n",
    "    group_responses.process(\n",
    "        [\n",
    "            {\n",
    "                \"generation\": \"Madrid\",\n",
    "                \"model_name\": \"meta-llama/Meta-Llama-3-8B-Instruct\",\n",
    "            },\n",
    "        ],\n",
    "        [\n",
    "            {\n",
    "                \"generation\": \"Barcelona\",\n",
    "                \"model_name\": \"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
    "            }\n",
    "        ],\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 评估响应\n",
    "\n",
    "为了构建我们的偏好数据集，我们需要评估模型生成的响应。我们将使用 [`meta-llama/Meta-Llama-3-70B-Instruct`](https://huggingface.co/meta-llama/Meta-Llama-3-70B-Instruct) 来进行此操作，应用 `UltraFeedback` 任务，根据不同维度（有用性、诚实性、遵循指令程度、真实性）对响应进行评分。\n",
    "\n",
    "- 组件：使用 `InferenceEndpointsLLM` 执行的 `UltraFeedback` 任务\n",
    "- 输入列：`instruction`，`generations`\n",
    "- 输出列：`ratings`，`rationales`，`distilabel_metadata`，`model_name`\n",
    "\n",
    "根据你的使用场景，你还可以使用任何你选择的 [其他 LLM](https://distilabel.argilla.io/latest/components-gallery/llms/) 来改进结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'instruction': \"What's the capital of Spain?\",\n",
       "  'generations': ['Madrid', 'Barcelona'],\n",
       "  'ratings': [5, 1],\n",
       "  'rationales': [\"The answer is correct, directly addressing the question, and is free of hallucinations or unnecessary details. It confidently provides the accurate information, aligning perfectly with the user's intent.\",\n",
       "   \"The answer is incorrect as Barcelona is not the capital of Spain. This introduces a significant inaccuracy, failing to provide helpful information and deviating entirely from the user's intent.\"],\n",
       "  'distilabel_metadata': {'raw_output_ultra_feedback_0': \"#### Output for Text 1\\nRating: 5 (Excellent)\\nRationale: The answer is correct, directly addressing the question, and is free of hallucinations or unnecessary details. It confidently provides the accurate information, aligning perfectly with the user's intent.\\n\\n#### Output for Text 2\\nRating: 1 (Low Quality)\\nRationale: The answer is incorrect as Barcelona is not the capital of Spain. This introduces a significant inaccuracy, failing to provide helpful information and deviating entirely from the user's intent.\"},\n",
       "  'model_name': 'meta-llama/Meta-Llama-3-70B-Instruct'}]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "evaluate_responses = UltraFeedback(\n",
    "    aspect=\"overall-rating\",\n",
    "    llm=InferenceEndpointsLLM(\n",
    "        model_id=\"meta-llama/Meta-Llama-3-70B-Instruct\",\n",
    "        tokenizer_id=\"meta-llama/Meta-Llama-3-70B-Instruct\",\n",
    "        generation_kwargs={\"max_new_tokens\": 512, \"temperature\": 0.7},\n",
    "    ),\n",
    "    pipeline=Pipeline(name=\"showcase-pipeline\"),\n",
    ")\n",
    "evaluate_responses.load()\n",
    "next(\n",
    "    evaluate_responses.process(\n",
    "        [\n",
    "            {\n",
    "                \"instruction\": \"What's the capital of Spain?\",\n",
    "                \"generations\": [\"Madrid\", \"Barcelona\"],\n",
    "            }\n",
    "        ]\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 转换为偏好数据集\n",
    "\n",
    "- 你可以使用 `chosen` 和 `rejected` 列自动将其转换为偏好数据集。\n",
    "    - 组件：`FormatTextGenerationDPO` 步骤\n",
    "    - 输入列：`instruction`，`generations`，`generation_models`，`ratings`\n",
    "    - 输出列：`prompt`，`prompt_id`，`chosen`，`chosen_model`，`chosen_rating`，`rejected`，`rejected_model`，`rejected_rating`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'instruction': \"What's the capital of Spain?\",\n",
       "  'generations': ['Madrid', 'Barcelona'],\n",
       "  'generation_models': ['Meta-Llama-3-8B-Instruct',\n",
       "   'Mixtral-8x7B-Instruct-v0.1'],\n",
       "  'ratings': [5, 1],\n",
       "  'prompt': \"What's the capital of Spain?\",\n",
       "  'prompt_id': '26174c953df26b3049484e4721102dca6b25d2de9e3aa22aa84f25ed1c798512',\n",
       "  'chosen': [{'role': 'user', 'content': \"What's the capital of Spain?\"},\n",
       "   {'role': 'assistant', 'content': 'Madrid'}],\n",
       "  'chosen_model': 'Meta-Llama-3-8B-Instruct',\n",
       "  'chosen_rating': 5,\n",
       "  'rejected': [{'role': 'user', 'content': \"What's the capital of Spain?\"},\n",
       "   {'role': 'assistant', 'content': 'Barcelona'}],\n",
       "  'rejected_model': 'Mixtral-8x7B-Instruct-v0.1',\n",
       "  'rejected_rating': 1}]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "format_dpo = FormatTextGenerationDPO(pipeline=Pipeline(name=\"showcase-pipeline\"))\n",
    "format_dpo.load()\n",
    "next(\n",
    "    format_dpo.process(\n",
    "        [\n",
    "            {\n",
    "                \"instruction\": \"What's the capital of Spain?\",\n",
    "                \"generations\": [\"Madrid\", \"Barcelona\"],\n",
    "                \"generation_models\": [\n",
    "                    \"Meta-Llama-3-8B-Instruct\",\n",
    "                    \"Mixtral-8x7B-Instruct-v0.1\",\n",
    "                ],\n",
    "                \"ratings\": [5, 1],\n",
    "            }\n",
    "        ]\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 或者，你可以使用 Argilla 手动标注数据并将其转换为偏好数据集。\n",
    "    - 组件：`PreferenceToArgilla` 步骤\n",
    "    - 输入列：`instruction`，`generations`，`generation_models`，`ratings`\n",
    "    - 输出列：`instruction`，`generations`，`generation_models`，`ratings`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "to_argilla = PreferenceToArgilla(\n",
    "    dataset_name=\"preference-dataset\",\n",
    "    dataset_workspace=\"argilla\",\n",
    "    api_url=\"https://[your-owner-name]-[your-space-name].hf.space\",\n",
    "    api_key=\"[your-api-key]\",\n",
    "    num_generations=2\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 运行管道"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以下是完整的管道定义："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "with Pipeline(name=\"generate-dataset\") as pipeline:\n",
    "\n",
    "    load_dataset = LoadDataFromHub(repo_id=\"argilla/10Kprompts-mini\")\n",
    "\n",
    "    generate_responses = [\n",
    "        TextGeneration(\n",
    "            llm=InferenceEndpointsLLM(\n",
    "                model_id=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n",
    "                tokenizer_id=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n",
    "                generation_kwargs={\"max_new_tokens\": 512, \"temperature\": 0.7},\n",
    "            )\n",
    "        ),\n",
    "        TextGeneration(\n",
    "            llm=InferenceEndpointsLLM(\n",
    "                model_id=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
    "                tokenizer_id=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n",
    "                generation_kwargs={\"max_new_tokens\": 512, \"temperature\": 0.7},\n",
    "            )\n",
    "        ),\n",
    "    ]\n",
    "\n",
    "    group_responses = GroupColumns(\n",
    "        columns=[\"generation\", \"model_name\"],\n",
    "        output_columns=[\"generations\", \"model_names\"],\n",
    "    )\n",
    "\n",
    "    evaluate_responses = UltraFeedback(\n",
    "        aspect=\"overall-rating\",\n",
    "        llm=InferenceEndpointsLLM(\n",
    "            model_id=\"meta-llama/Meta-Llama-3-70B-Instruct\",\n",
    "            tokenizer_id=\"meta-llama/Meta-Llama-3-70B-Instruct\",\n",
    "            generation_kwargs={\"max_new_tokens\": 512, \"temperature\": 0.7},\n",
    "        )\n",
    "    )\n",
    "\n",
    "    format_dpo = FormatTextGenerationDPO()\n",
    "\n",
    "    to_argilla = PreferenceToArgilla(\n",
    "        dataset_name=\"preference-dataset\",\n",
    "        dataset_workspace=\"argilla\",\n",
    "        api_url=\"https://[your-owner-name]-[your-space-name].hf.space\",\n",
    "        api_key=\"[your-api-key]\",\n",
    "        num_generations=2\n",
    "    )\n",
    "\n",
    "    for task in generate_responses:\n",
    "        load_dataset.connect(task)\n",
    "        task.connect(group_responses)\n",
    "    group_responses.connect(evaluate_responses)\n",
    "    evaluate_responses.connect(format_dpo, to_argilla)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行管道并生成偏好数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "distiset = pipeline.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "让我们检查偏好数据集！如果你已经将数据加载到 Argilla，你可以通过 [在 Argilla UI 中开始标注](https://docs.argilla.io/latest/how_to_guides/annotate/)。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以将数据集推送到 Hub 与社区共享，并 [嵌入它以探索数据](https://huggingface.co/docs/hub/datasets-viewer-embed)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "distiset.push_to_hub(\"[your-owner-name]/example-preference-dataset\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<iframe\n",
    "  src=\"https://huggingface.co/datasets/distilabel-internal-testing/example-generate-preference-dataset/embed/viewer/format_text_generation_d_p_o_0/train\"\n",
    "  frameborder=\"0\"\n",
    "  width=\"100%\"\n",
    "  height=\"560px\"\n",
    "></iframe>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在本教程中，我们展示了使用 Distilabel 构建生成偏好数据集的流水线的详细步骤。您可以根据自己的使用案例定制此流水线，并通过 Hugging Face Hub 与社区共享您的数据集，或使用它们训练 DPO 或 ORPO 模型。\n",
    "\n",
    "我们使用了一个包含提示的数据集，通过无服务器的 Hugging Face 推理 API 使用两个不同的模型生成响应。接下来，我们使用第三个模型根据 UltraFeedback 标准对响应进行了评估。最后，我们将数据转换为偏好数据集，并使用 Argilla 进行进一步的整理。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "distilabel-tutorials",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
